from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, JSON, DateTime, Table
from sqlalchemy.orm import relationship
from datetime import datetime
from database import Base

class Menu(Base):
    __tablename__ = "menus"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    path = Column(String(255))
    component = Column(String(255))
    icon = Column(String(100))
    parent_id = Column(Integer, ForeignKey('menus.id'))
    sort_order = Column(Integer, default=0)
    is_visible = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关系
    parent = relationship("Menu", remote_side=[id], backref="children")
    # 权限关联（一个菜单可以有多个权限）
    permissions = relationship("Permission", secondary="menu_permissions", back_populates="menus")

# 菜单-权限关联表
menu_permissions = Table(
    'menu_permissions',
    Base.metadata,
    Column('menu_id', Integer, ForeignKey('menus.id'), primary_key=True),
    Column('permission_id', Integer, ForeignKey('permissions.id'), primary_key=True)
)

# 使用延迟导入避免循环引用
from sqlalchemy.ext.declarative import declared_attr

# 延迟导入Permission模型并设置关系
from sqlalchemy.orm import relationship
from models.user import Permission

# 直接添加menus关系到Permission模型
if not hasattr(Permission, 'menus'):
    Permission.menus = relationship("Menu", secondary=menu_permissions, back_populates="permissions")